
package com.example.casper.jnuexperiment2025.dataop;

import android.content.Context;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DataBank {
    private static final String DATA_FILENAME = "books.data";
    public List<Book> loadBooks(Context context) {
        List<Book> books = new ArrayList<>();
        try {
            FileInputStream fileIn = context.openFileInput(DATA_FILENAME);
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);
            books = (List<Book>) objectIn.readObject();
            objectIn.close();
            fileIn.close();
            Log.d("DataBank", "数据加载成功，图书数量: " + books.size());
        } catch (IOException | ClassNotFoundException e) {
            Log.e("DataBank", "加载数据失败，将返回空列表", e);
            
        }
        return books;
    }

    public void saveBooks(Context context, List<Book> books) {
        try {
            FileOutputStream fileOut = context.openFileOutput(DATA_FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(books);
            out.close();
            fileOut.close();
            Log.d("DataBank", "数据保存成功，图书数量: " + books.size());
        } catch (IOException e) {
            Log.e("DataBank", "保存数据失败", e);
        }
    }
}